import type { Component } from "vue";
import { defineAsyncComponent } from "vue";
import {
  createRouter as _createRouter,
  createWebHashHistory,
  createWebHistory,
  Router,
} from "vue-router";
// eslint-disable-next-line no-unused-expressions
("不需要修改，自动导入pages文件夹所有内容");

// Auto generates routes from vue files under ./pages
// https://vitejs.dev/guide/features.html#glob-import
// @ts-ignore
// const pages = import.meta.glob("/pages/**/*.vue");
/**
 * const pages = import.meta.glob("/pages/**\/*.vue");
 */
export type Pages = {
  [key: string]: ImportComponent;
};

export interface ImportComponent {
  (): Promise<Component>;
}

/**
 *
 * @param pages import.meta.glob("/pages/\*\*\/\*.vue");
 * @param useDefineAsyncComponent 如果是，在引入该page时defineAsyncComponent(pages[path])，否则直接为pages[path]
 * @returns
 */
export function routes(
  pages: Pages,
  useDefineAsyncComponent = false
): {
  path: string;
  name?: string;
  component: any;
}[] {
  return Object.keys(pages).map((path) => {
    const regTest = /pages(?<page>(.*))\.vue$/;
    const regDynamic = /^\[(?<name>.*)\]/g;
    let {
      // @ts-ignore
      groups: { page },
    } = regTest.exec(path);
    page = page
      .split("/")
      .map((e: string) =>
        e.replace(regDynamic, (str) => {
          const {
            // @ts-ignore
            groups: { name },
          } = regDynamic.exec(str);
          return `:${name}`;
        })
      )
      .join("/");
    if (path === "/pages/[...all].vue") {
      return {
        path: "/:pathMatch(.*)*",
        name: "NotFound",
        component: useDefineAsyncComponent
          ? defineAsyncComponent(pages[path])
          : pages[path], // () => import('./pages/*.vue')
      };
    } else {
      return {
        path: page === "/home" ? "/" : page,
        component: useDefineAsyncComponent
          ? defineAsyncComponent(pages[path])
          : pages[path], // () => import('./pages/*.vue')
      };
    }
  });
}

/**
 * 自动根据pages文件夹下的vue文件生成路由
 * @param pages import.meta.glob("/pages/\*\*\/\*.vue");
 * @param useDefineAsyncComponent 如果是，在引入该page时defineAsyncComponent(pages[path])，否则直接为pages[path]
 * @returns {Router} HistoryMode路由
 */
export function createHistoryRouter(
  pages: Pages,
  useDefineAsyncComponent = false
): Router {
  return _createRouter({
    // use appropriate history implementation for server/client
    // import.meta.env.SSR is injected by Vite.
    // history: import.meta.env.SSR ? createMemoryHistory() : createWebHistory(),
    history: createWebHistory(),
    routes: routes(pages, useDefineAsyncComponent),
  });
}

/**
 * 自动根据pages文件夹下的vue文件生成路由
 * @param pages import.meta.glob("/pages/\*\*\/\*.vue");
 * @param useDefineAsyncComponent 如果是，在引入该page时defineAsyncComponent(pages[path])，否则直接为pages[path]
 * @returns {Router} hashMode路由
 */
export function createHashRouter(
  pages: Pages,
  useDefineAsyncComponent = false
): Router {
  return _createRouter({
    // use appropriate history implementation for server/client
    // import.meta.env.SSR is injected by Vite.
    // history: import.meta.env.SSR ? createMemoryHistory() : createWebHistory(),
    history: createWebHashHistory(),
    routes: routes(pages, useDefineAsyncComponent),
  });
}

export interface CreateRouterOptions {
  /**
   * 传入 import.meta.glob("/pages/\*\*\/\*.vue")
   */
  pages: Pages;
  /**
   * 是否为createWebHashHistory
   */
  useHash?: boolean;
  /**
   * 是否使用 component : defineAsyncComponent(pages[path]) 作为路由组件
   */
  useDefineAsyncComponent?: boolean;
}
/**
 * 生成默认自动导入pages的vue-router
 * @param options 配置
 * @returns Router实例
 */
export function createRouter({
  pages,
  useHash = false,
  useDefineAsyncComponent = false,
}: CreateRouterOptions) {
  return _createRouter({
    history: useHash ? createWebHashHistory() : createWebHistory(),
    routes: routes(pages, useDefineAsyncComponent),
  });
}

export default createRouter;
